import { Form, Input, Button, Table, Popconfirm, Space, message, Modal, Select, Pagination } from 'antd'
import http from '../../utils/http'
import { useEffect, useState } from 'react';
import store from '../../store/index'
import './role_management.scss'
const { Option } = Select;
// let newSelectData=[];
const RoleTable = ({ setState }) => {
    const [form] = Form.useForm();
    const [editForm] = Form.useForm();
    const [searchForm] = Form.useForm();
    //后端时间戳转时间的方法
    const toTimes = (value) => {
        if (value) {
            let date = new Date(value)
            let y = date.getFullYear()  //获取年份
            let m = date.getMonth() + 1  //获取月份
            m = m < 10 ? "0" + m : m  //月份不满10天显示前加0
            let d = date.getDate()  //获取日期
            d = d < 10 ? "0" + d : d  //日期不满10天显示前加0
            return y + "-" + m + "-" + d
        }
        else {
            return null
        }
    }
    //渲染表格
    const showTable=(data)=>{
        let arr = data.map((v, i) => {
            return {
                key: v.roId,
                roName: v.roName,
                roType: v.roType == 1 ? '系统角色' : '普通角色',
                roState: v.roState == 1 ? '停用' : '启用',
                roCreatetime: toTimes(v.roCreatetime),
                adId: v.adId,
                roUpdatetime: toTimes(v.roUpdatetime)
            }
        })
        setData(arr);
    }
    //获取数据
    const [data, setData] = useState([])
    const [total, setTotal] = useState(0)
    useEffect(() => {
        // console.log(1)
        getData()
    }, [])
    const getData = () => {
        http({
            url: '/roleinfo/roleInfoByName',
            method: 'post'
        }).then((res) => {
            console.log(res)
            if (res.code === 200) {
                if (res.data.records) {
                    setTotal(res.data.total)
                    showTable(res.data.records)
                    // sessionStorage.setItem('roleTable', JSON.stringify(arr));
                }
            }
        })
    }
    //修改Modal的样式
    const layout = {
        labelCol: {
            span: 8,
        },
        wrapperCol: {
            span: 14,
        },
    };
    const tailLayout = {
        wrapperCol: {
            offset: 8,
            span: 16,
        },
    };
    //切换为新增组件
    const xinzeng = () => {
        setState(2)
    }
    const search = () => {
        let Inp = searchForm.getFieldsValue(true).username
        console.log(Inp)
        let chajson = { 'roName': Inp }
        console.log(chajson)
        http({
            url: '/roleinfo/roleInfoByName',
            method: 'post',
            params: chajson
        }).then((res) => {
            console.log('cha', res)
            if (res.data.records) {
                showTable(res.data.records)
            }
            else {
                setData([]);
            }
        })
    }
    //重置按钮
    const resize = () => {
        searchForm.getFieldsValue(true).username = ''
        getData()
    }
    //修改id
    const [editId, seteditId] = useState('')
    //修改确定按钮
    const onFinish = (values) => {
        // console.log(editId)
        // console.log(typeof values.roType)
        // console.log(values.roType,values.roType instanceof String)
        if (values.roType == '普通角色') {
            values.roType = 0;
        } else if (values.roType == '系统角色') {
            values.roType = 1;
        }
        if (values.roState == '启用') {
            values.roState = 0;
        } else if (values.roState == '停用') {
            values.roState = 1;
        }
        values.roId = editId
        console.log(values);
        http({
            url: '/roleinfo/updateRoleInfo',
            method: 'post',
            data: values
        }).then((res) => {
            // console.log(res)
            if (res.code === 200) {
                form.resetFields();
                seteditModel(false)
                getData()
            }

        })
    };
    //取消修改
    const quxiao = () => {
        seteditModel(false)
    }
    //设置修改Modal的显示与隐藏
    const [editModel, seteditModel] = useState(false)
    const openEditBox = (a, b) => {
        //获取当前时间
        let yy = new Date().getFullYear();
        let mm = new Date().getMonth() + 1;
        mm = mm < 10 ? '0' + mm : mm
        // let mm
        // let dd
        // if(m<10){
        //     mm='0'+m
        // }
        let dd = new Date().getDate();
        dd = dd < 10 ? '0' + dd : dd
        // if(d<10){
        //     dd='0'+d
        // }
        let gettime = yy + "-" + mm + "-" + dd;
        console.log(a, b, gettime)
        editForm.setFieldsValue({
            roName: b.roName,
            roType: b.roType,
            roState: b.roState,
            roCreatetime: b.roCreatetime,
            adId: b.adId,
            roUpdatetime: gettime
        })
        seteditModel(true)
        seteditId(b.key)
    }
    //取消删除
    function cancel(e) {
    }
    //删除按钮
    function confirm(a, b) {
        // console.log('newSelectData',newSelectData)
        let id = [];
        if (b) {
            id.push(b.key)
        } else {
            id = newSelectData.map(v => v.key)
        }
        http({
            url: '/roleinfo/deleteRoleInfo',
            method: 'post',
            data: id
        }).then((res) => {
            console.log(res)
            if (res.code === 200) {
                message.success('删除成功！');
                getData()
            }
        })
        // console.log('id',id)
        setselectedRowKeys([])
    }
    //表格头部
    const columns = [
        {
            title: '角色名称',
            dataIndex: 'roName',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '角色类型',
            dataIndex: 'roType',
        },
        {
            title: '启用状态',
            dataIndex: 'roState',
        },
        {
            title: '创建时间',
            dataIndex: 'roCreatetime',
        },
        {
            title: '操作人',
            dataIndex: 'adId',
        },
        {
            title: '更新时间',
            dataIndex: 'roUpdatetime',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => { openEditBox(text, record) }}>修改</a>
                    <Popconfirm
                        title="确定要删除吗?"
                        onConfirm={() => { confirm(text, record) }}
                        onCancel={cancel}
                        okText="Yes"
                        cancelText="No"
                        disabled={record.roState == '停用' ? true : false}
                    >
                        <a href="#" disabled={record.roState == '停用' ? true : false}>删除</a>
                    </Popconfirm>
                </Space>
            ),
        },
    ];
    //将选中的数组的key值存放到新的数组中
    const [newSelectData, setnewSelectData] = useState([])
    const [selectedRowKeys, setselectedRowKeys] = useState([])
    const rowSelection = {
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            setselectedRowKeys(selectedRowKeys)
            // newSelectData=selectedRows
            setnewSelectData(selectedRows)
            // console.log(selectedRowKeys)
            // console.log(newSelectData)
        },
        getCheckboxProps: (record) => (
            {
                disabled: record.roState === '停用'
            })
    };
    //改变页码
    function onChange(pageNumber) {
        console.log('Page: ', pageNumber);
        let pageChange = { 'current': pageNumber }
        console.log(pageChange)
        http({
            url: '/roleinfo/roleInfoByName',
            method: 'post',
            params: pageChange
        }).then((res) => {
            console.log(res)
            // setData(res.data.records)
            showTable(res.data.records)
        })
    }
    return <div className='roleContent'>
        <Form form={form} name="horizontal_login" layout="inline" className='title'>
            <Form.Item
                name="username">
                <div className='kuai'>
                    <span></span>
                    <span>角色信息管理</span>
                </div>
            </Form.Item>
            <Form.Item className='btn'>
                <div>
                    <Button className='cha'
                        type="primary"
                        onClick={xinzeng}>新增</Button>
                    <Popconfirm title="确定要将他们全部删除吗？"
                        onConfirm={() => { confirm() }}
                        onCancel={cancel} okText="Yes" cancelText="No">
                        <a href="#"><Button className='resize' type="primary">批量删除</Button></a>
                    </Popconfirm>

                </div>

            </Form.Item>
        </Form>
        <div className='biao'>
            <Form form={searchForm} name="horizontal_login" layout="inline" className='Role'>
                <Form.Item
                    name="username"
                    label='角色名称'
                ><Input placeholder='请输入角色姓名' />
                </Form.Item>
                <Form.Item className='btn'>
                    <div>
                        <Button className='cha'
                            type="primary"
                            onClick={search}>查询</Button>
                        <Button className='resize' onClick={resize} type="primary">重置</Button>
                    </div>

                </Form.Item>
            </Form>
            <Table className='table1'
                rowSelection={{
                    ...rowSelection,
                }}
                columns={columns}
                dataSource={data}
                pagination={false}
            />
            <Pagination className='page'
                total={total} onChange={onChange} />
        </div>
        <Modal
            title="修改"
            visible={editModel}
            footer={null}
            onCancel={quxiao}
        >
            <Form {...layout} form={editForm} name="control-hooks" onFinish={onFinish}>
                <Form.Item
                    name="roName"
                    label="角色名称"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="roType"
                    label="角色类型"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Select
                        placeholder="请选择创建状态"
                        allowClear
                    >
                        <Option value="0">普通角色</Option>
                        <Option value="1">系统角色</Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    name="roState"
                    label="启用状态"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Select
                        placeholder="请选择状态"
                        allowClear
                    >
                        <Option value="0">启用</Option>
                        <Option value="1">禁用</Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    name="roCreatetime"
                    label="创建时间"
                // rules={[
                //     {
                //         required: true,
                //     },
                // ]}
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    name="adId"
                    label="操作人"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    name="roUpdatetime"
                    label="更新时间"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                    <Button htmlType="button" onClick={quxiao} style={{ marginLeft: '20px' }}>
                        取消
                    </Button>
                </Form.Item>
            </Form>
        </Modal>
    </div>
};
export default RoleTable